//
//  GoogleLocationNameDownloader.h
//  iCitySuzhou_iPad
//
//  Created by Jason Liu on 12/31/11.
//  Copyright 2011 Yulong. All rights reserved.
//

#import "GoogleLocationNameDownloader.h"
#import	"AppDelegate.h"
#import <CFNetwork/CFNetwork.h>
#import "ChineseToPinyin.h"
#import "JSON.h"
#import "Constant.h"

#define DefaultLocationCity @"苏州"
#define CurrentCommentLocationCityKey @""

@implementation GoogleLocationNameDownloader

@synthesize LocationNameConnection, LocationNameData;
@synthesize delegate, sourceTag, paperURL;
@synthesize streetName;


- (void)cannotLocateAddressHandling
{
    locationName = DefaultLocationCity;

    // FOR COMMENT
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    [standardUserDefaults setObject:@"火星" forKey:CurrentCommentLocationCityKey];
    [standardUserDefaults synchronize];
}


// 根据经纬度从google获取相映的JSON地址信息
- (void)getLocationNameFromJSON
{
    NSString *originalLocationName = @"苏州市";
    NSString *jsonStr = [[[NSString alloc]initWithData:LocationNameData encoding:NSUTF8StringEncoding]autorelease];
    locationName = DefaultLocationCity;
    self.streetName = @"";
    
    if (jsonStr && ![jsonStr isEqualToString:@""])
    {
        NSDictionary *dict = [jsonStr JSONValue];
		NSString *resultStatus = [dict objectForKey:@"status"];
        if (![resultStatus isEqualToString:@"OK"])
        {
            [self cannotLocateAddressHandling];
            return;
        }
        NSArray *resultArray = (NSArray *)[dict objectForKey:@"results"];
        if (!resultArray)
        {
            [self cannotLocateAddressHandling];
            return;
        }
        dict = [resultArray objectAtIndex:0];
        if (!dict)
        {
            [self cannotLocateAddressHandling];
            return;
        }
        NSString *routeStr = nil, *neighborhoodStr = nil, *sublocalityStr = nil, *localityStr = nil, *administrative_area_level_1Str = nil, *countryStr = nil;
        
        NSArray *addressComponents = [dict objectForKey:@"address_components"];
        if (addressComponents.count > 0)
        {
            NSDictionary *tempDict;
            int count = addressComponents.count;
            for (int i = 0; i < count; i++)
            {
                tempDict = [addressComponents objectAtIndex:i];
                if (tempDict)
                {
                    NSArray *tempArray = (NSArray *)[tempDict objectForKey:@"types"];
                    if (tempArray && tempArray.count > 0)
                    {
                        NSString *typeStr = [tempArray objectAtIndex:0];
                        if ([typeStr isEqualToString:@"route"])
                        {
                            routeStr = [tempDict objectForKey:@"long_name"];
                        }
                        else if ([typeStr isEqualToString:@"neighborhood"])
                        {
                            neighborhoodStr = [tempDict objectForKey:@"long_name"];
                        }
                        else if ([typeStr isEqualToString:@"sublocality"])
                        {
                            sublocalityStr = [tempDict objectForKey:@"long_name"];
                        }
                        else if ([typeStr isEqualToString:@"locality"])
                        {
                            localityStr = [tempDict objectForKey:@"long_name"];
                        }
                        else if ([typeStr isEqualToString:@"administrative_area_level_1"])
                        {
                            administrative_area_level_1Str = [tempDict objectForKey:@"long_name"];
                        }
                        else if ([typeStr isEqualToString:@"country"])
                        {
                            countryStr = [tempDict objectForKey:@"long_name"];
                        }
                    }
                }
            }
        }
        
        //street name start
        if (localityStr.length > 0)
        {
            self.streetName = localityStr;
        }
        if (sublocalityStr.length > 0)
        {
            self.streetName = [self.streetName stringByAppendingString:sublocalityStr];
        }
        if (neighborhoodStr.length > 0)
        {
            self.streetName = [self.streetName stringByAppendingString:neighborhoodStr];
        }
        if (routeStr.length > 0)
        {
            self.streetName = [self.streetName stringByAppendingString:routeStr];
        }
        //street name end
        if (localityStr.length > 0)
        {
            //此处检查localityStr是否以市结尾，如：苏州市，如果没有则添加以和以前代码匹配
            if (![localityStr hasSuffix:@"市"])
            {
                localityStr = [NSString stringWithFormat:@"%@市", localityStr];
            }
            locationName = localityStr;
            originalLocationName = localityStr;
            if (sublocalityStr.length > 0)
            {
                originalLocationName = [NSString stringWithFormat:@"%@%@", originalLocationName, sublocalityStr];
                if (neighborhoodStr.length > 0) {
                    originalLocationName = [NSString stringWithFormat:@"%@%@", originalLocationName, neighborhoodStr];
                }
            }
        }
        else
        {
            [self cannotLocateAddressHandling];
            return;
        }
    }
    /*
    if (jsonStr && ![jsonStr isEqualToString:@""])
    {
        NSDictionary *dict = [jsonStr JSONValue];
		
        NSArray *locationNames = [dict objectForKey:@"Placemark"];
        if (locationNames.count > 0)
        {
            dict = [locationNames objectAtIndex:0];
            if (!dict)
            {
                [self cannotLocateAddressHandling];
                return;
            }
            dict = [dict objectForKey:@"AddressDetails"];
			
			//NSLog(@"AddressDetails = %@", dict);
            if (!dict)
            {
                [self cannotLocateAddressHandling];
                return;
            }
            dict = [dict objectForKey:@"Country"];
			
			//NSLog(@"Country = %@", dict);
            if (!dict)
            {
                [self cannotLocateAddressHandling];
                return;
            }
            dict = [dict objectForKey:@"AdministrativeArea"];
			
			//NSLog(@"AdministrativeArea = %@", dict);
            if (!dict)
            {
                [self cannotLocateAddressHandling];
                return;
            }
            dict = [dict objectForKey:@"Locality"];
			
			//NSLog(@"Locality = %@", dict);
            if (!dict)
            {
                [self cannotLocateAddressHandling];
                return;
            }
            locationName = [dict objectForKey:@"LocalityName"];
            originalLocationName = [dict objectForKey:@"LocalityName"];
            
            NSDictionary *dictDependent = [dict objectForKey:@"DependentLocality"];
            if (dictDependent)
            {
                NSString *suburbName = [dictDependent objectForKey:@"DependentLocalityName"];
                if (suburbName)
                {
                    if (![suburbName isEqualToString:@""]) {
                        originalLocationName = [NSString stringWithFormat:@"%@%@", originalLocationName, suburbName];
                    }
                }
            }
            // 注释掉精确到街道的定位，以备后用。- END
            
            //精确到街道的定位
            if (dictDependent) {
                NSString *suburbName = [dictDependent objectForKey:@"DependentLocalityName"];
                dictDependent = [dictDependent objectForKey:@"Thoroughfare"];
                if ((NSNull *)dictDependent != [NSNull null] && dictDependent) {
                    NSString *tempStreetName = [dictDependent objectForKey:@"ThoroughfareName"];
                    if ([suburbName length] > 0) {
                        self.streetName = suburbName;
                    }
                    if ([tempStreetName length] > 0) {
                        self.streetName = [self.streetName stringByAppendingFormat:@"%@", tempStreetName];
                    }
                }
            }

        }
    }
    */
    // FOR COMMENT
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    [standardUserDefaults setObject:originalLocationName forKey:CurrentCommentLocationCityKey];
    [standardUserDefaults synchronize];

}

// 根据地址信息获取拼音信息
- (void)convertIntoPYName
{
    locationName = [ChineseToPinyin pinyinFromChiniseString:locationName];
}

- (void)dealloc
{	
	[LocationNameConnection cancel];
    [LocationNameConnection release];
    [LocationNameData release];
	[paperURL release];
	self.streetName = nil;[streetName release];
    [super dealloc];
}

// 根据经纬度从服务器获取拼音字符串
- (void)startLocationNameDownload:(CLLocationCoordinate2D)coord_
{	
    coord = coord_;
	//NSString *thePaperURL = [NSString stringWithFormat:@"http://ditu.google.cn/maps/geo?output=json&q=%lf,%lf&hl=zh-CN", coord.latitude, coord.longitude];
    NSString *thePaperURL = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/geocode/json?latlng=%lf,%lf&sensor=false&language=zh-CN", coord.latitude, coord.longitude];
	NSURLRequest *urlRequest = [NSURLRequest requestWithURL:
								[NSURL URLWithString:thePaperURL]];
	self.LocationNameConnection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
	NSAssert(self.LocationNameConnection != nil, @"Failure to create URL connection.");
}

- (void)cancelLocationNameDownload
{
    [self.LocationNameConnection cancel];
    self.LocationNameConnection = nil;
    self.LocationNameData = nil;
}

#pragma mark -
#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	NSHTTPURLResponse * httpResponse;
	httpResponse = (NSHTTPURLResponse *) response;
	assert( [httpResponse isKindOfClass:[NSHTTPURLResponse class]] );
	// Check that the HTTP status code is 2xx.  If it isn't, we fail right now.
	if ((httpResponse.statusCode / 100) != 2)
	{
        if ([delegate respondsToSelector:@selector(LocationNameLoadFailed:)]) {
            [delegate LocationNameLoadFailed:nil];
        }
		[connection cancel];
		return;
	}
	
    self.LocationNameData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [LocationNameData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	self.LocationNameData = nil;
    self.LocationNameConnection = nil;
	if ([delegate respondsToSelector:@selector(LocationNameLoadFailed:)]) {
        [delegate LocationNameLoadFailed:error];
    }
	[self startLocationNameDownload:coord];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.LocationNameConnection = nil;
	
    // 获取地址信息
    [self getLocationNameFromJSON];
    
	// 转换成地址信息的大写拼音
    //[self convertIntoPYName];
	if ([delegate respondsToSelector:@selector(LocationNameDidLoad:)])
    {
        [delegate LocationNameDidLoad:locationName];
    }
    
    //返回给需要街道信息的对象
    if ([delegate respondsToSelector:@selector(StreetNameDidLoad:)])
    {
        [delegate StreetNameDidLoad:self.streetName];
    }
}
@end
